package com.dt.app.exception;

import com.dt.app.common.response.ResultUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 异常处理器
 * @author DT
 * @date 2021/6/3 21:33
 */
@CommonsLog
@RestControllerAdvice
public class CmsExceptionHandler {

    /**
     *  通用异常处理
     */
    @ExceptionHandler(Exception.class)
    public ResultUtil<?> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultUtil.error(e.getMessage());
    }

    /**
     *  数据校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultUtil<String> bindExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        String message = "";
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            for (ObjectError error : errors) {
                FieldError fieldError = (FieldError) error;
                message = fieldError.getDefaultMessage();
            }
        }
        log.error("错误原因->>>"+e.getMessage());
        log.error("函数方法->>>"+e.getParameter());
        log.error("参数校验->>>"+message);
        return ResultUtil.error(message);
    }
}
